package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.pojo.Admin;
import com.tanhua.model.vo.AdminVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    //    用户登录
    public Map login(Map map) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String verificationCode = (String) map.get("verificationCode");
        String uuid = (String) map.get("uuid");
        if(StringUtils.isBlank(username)||StringUtils.isBlank(password)){
            throw new BusinessException("用户名或者密码为空");
        }
        if(StringUtils.isBlank(verificationCode)){
            throw new BusinessException("验证码为空");
        }
        String redisCode = redisTemplate.opsForValue().get(Constants.CAP_CODE + uuid);
        if(!redisCode.equals(verificationCode)||StringUtils.isBlank(redisCode)){
            throw new BusinessException("验证码错误");
        }
        redisTemplate.delete(Constants.CAP_CODE + uuid);
        Admin admin = adminMapper.selectOne(Wrappers.lambdaQuery(Admin.class)
                .eq(Admin::getUsername, username));
        if(admin==null||!admin.getPassword().equals(SecureUtil.md5(password))){
            throw new BusinessException("用户名或者密码错误");
        }
        Map<String,Object> params = new HashMap<>();
        params.put("id",admin.getId());
        params.put("username",admin.getUsername());
        String token = JwtUtils.getToken(params);
        Map result = new HashMap<>();
        result.put("token",token);
        return result;
    }

    //    获取管理员信息
    public AdminVo profile() {
        Admin admin = adminMapper.selectOne(Wrappers.lambdaQuery(Admin.class)
                .eq(Admin::getId, AdminHolder.getUserId()));
        return AdminVo.init(admin);
    }

}
